package com.ruoyi.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class CustomWebSocketHandler extends TextWebSocketHandler {

    private final List<WebSocketSession> sessions = new ArrayList<>();

    // 收到客户端连接触发
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session);
        log.info("客户端连接:" + session.getId());
    }

    // 收到客户端消息触发
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
        String payload = message.getPayload();
        log.info("收到客户端消息:" + payload);
        sendTextMessage(session, payload);
    }

    // 客户端断开触发
    @Override
    public void afterConnectionClosed(WebSocketSession session, org.springframework.web.socket.CloseStatus status) throws Exception {
        sessions.remove(session);
        log.info("客户端断开:" + session.getId());
    }

    // 发送文本消息到指定客户端
    public void sendTextMessage(WebSocketSession session, String message) {
        try {
            if (session.isOpen()) {
                session.sendMessage(new TextMessage(message));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 发送文本消息到所有客户端
    public void sendTextMessageToAll(String message) {
        for (WebSocketSession session : sessions) {
            sendTextMessage(session, message);
        }
    }

    // 发送二进制消息到指定客户端
    public void sendBinaryMessage(WebSocketSession session, byte[] data) {
        try {
            if (session.isOpen()) {
                session.sendMessage(new BinaryMessage(data));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 发送二进制消息到所有客户端
    public void sendBinaryMessageToAll(byte[] data) {
        for (WebSocketSession session : sessions) {
            sendBinaryMessage(session, data);
        }
    }
}
